<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="学号" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="系部" prop="college">
                <el-input v-model="queryParams.college" placeholder="请输入系部" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="荣誉名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['labour:index:add']"
                    @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" v-hasPermi="['labour:index:delete']"
                    :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" v-hasPermi="['labour:index:import']"
                    @click="handleImport">导入</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="affirmList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="id" align="center" prop="id" /> -->
            <el-table-column label="学号" align="center" prop="userName" />
            <el-table-column label="姓名" align="center" prop="nickName" />
            <el-table-column label="班级" align="center" prop="className" />
            <el-table-column label="系部" align="center" prop="college" />
            <!-- <el-table-column label="学期" align="center" prop="schoolYear" /> -->
            <el-table-column label="荣誉名称" align="center" prop="name" />
            <el-table-column label="荣誉类型" align="center" prop="typeName" />
            <el-table-column label="申报级别" align="center" prop="declareLevelName" />
            <el-table-column label="获得时间" align="center" prop="joinDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.joinDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column prop="status" label="状态" width="150" align="center">
                <template slot-scope="scope">
                    <dict-tag v-if="scope.row.status!=2" :options="dict.type.labour_status" :value="scope.row.status" />
                    <el-tooltip v-if="scope.row.status==2" class="item" effect="dark" :content="scope.row.auditOpinion" placement="top">
                        <dict-tag :options="dict.type.labour_status" :value="scope.row.status" />
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-s-claim" v-if="scope.row.status == 0"
                        v-hasPermi="['labour:index:status']" @click="handleStatus(scope.row)">审核</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.status != 1"
                        v-hasPermi="['labour:index:edit']" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" v-hasPermi="['labour:index:delete']"
                        @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改个人荣誉认定对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="学号" prop="userName">
                    <el-select v-model="form.userName" filterable remote reserve-keyword placeholder="请输入关键词"
                        :remote-method="remoteMethod" :loading="searchLoading">
                        <el-option v-for="(item, index) in options" :key="index" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="荣誉名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入荣誉名称" style="width: 75%" />
                </el-form-item>
                <el-form-item label="荣誉类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择" value-key="id" @change="changeProject($event)" clearable>
                        <el-option v-for="option in typeGradeList" :key="option.type" :label="option.typeNme"
                            :value="option.type"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="活动类型" prop="activityContent">
                    <el-select disabled v-model="formModel.activityContent" placeholder="请选择活动类型" style="width: 100%"
                        @change="changeContent($event)">
                        <el-option v-for="item in ActivityContentOptions" :key="item.activityType"
                            :label="item.activityTypeName" :value="item.activityType" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="申报级别" prop="declareLevel">
                    <el-select v-model="form.declareLevel" placeholder="请选择类型">
                        <el-option v-for="item in selGradeScore" :key="item.grade"
                            :label="item.gradeName + '-' + item.mark + '学分'" :value="item.grade" />
                    </el-select>
                </el-form-item>

                <el-form-item label="获得时间" prop="joinDate">
                    <el-date-picker clearable v-model="form.joinDate" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择获得时间">
                    </el-date-picker>
                </el-form-item>

                <!-- <el-form-item label="申报级别" prop="declareLevel">
                    <el-select v-model="form.declareLevel" placeholder="请选择申报级别" clearable>
                        <el-option v-for="dict in dict.type.affirm_honor_level" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item> -->

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog title="导入" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <!-- <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                    </div> -->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                        @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 审核对话框 -->
        <el-dialog :title="title" :visible.sync="checkopen" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item v-if="isRefuse" label="审核意见" prop="auditOpinion">
                    <el-input v-model="form.auditOpinion" placeholder="请输入审核意见" />
                </el-form-item>
                <el-form-item label="审核结果" prop="status">
                    <el-button type="primary" @click="submitFormE(1)" :plain="!isPass">审核通过</el-button>
                    <el-button type="primary" @click="submitFormE(2)" :plain="!isRefuse">审核拒绝</el-button>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="statusSubmitForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listAffirm, getAffirm, delAffirm, addAffirm, updateAffirm, treeSelectProject, getstudentmanager, listTypeGrade, auditAffirm } from "@/api/labour/affirm";
import { mapGetters } from 'vuex';
import { getToken } from '@/utils/auth';

export default {
    name: "Affirm",
    dicts: ['honor_affirm_status', 'affirm_honor_level', 'labour_status'],
    computed: {
        ...mapGetters(['name']),
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            searchLoading: false,
            // 总条数
            total: 0,
            // 个人荣誉认定表格数据
            affirmList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                userName: null,
                nickName: null,
                college: null,
                schoolYear: null,
                name: null,
                childProject: null,
                joinDate: null,
                joinDuration: null,
                declareLevel: null,
                accessoryUrl: null,
                status: null,
                auditUser: null,
                auditTime: null,
                auditOpinion: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                userName: [
                    { required: true, message: "学号不能为空", trigger: "blur" }
                ],
                name: [
                    { required: true, message: "荣誉名称不能为空", trigger: "change" }
                ],
                type: [
                    { required: true, message: "荣誉类型不能为空", trigger: "change" }
                ],
                declareLevel: [
                    { required: true, message: "申报级别不能为空", trigger: "change" }
                ],
                joinDate: [
                    { required: true, message: "获得时间不能为空", trigger: "change" }
                ],
                status: [
                    { required: true, message: "审核状态不能为空", trigger: "change" }
                ],
                auditOpinion: [
                    { required: true, message: "拒绝理由不能为空", trigger: "change" }
                ],
                accessoryUrl: [
                    { required: true, message: "佐证材料不能为空", trigger: "change" }
                ],
            },
            //荣誉称号下拉数据
            selHonorScore: [
                { range: '院级', score: '1' },
                { range: '校级', score: '2' },
                { range: '市级', score: '3' },
                { range: '省级及以上', score: '4' },
            ],
            // 参加竞赛下拉数据
            selMatchScore: [
                { range: '国一', score: '8' },
                { range: '国二', score: '7' },
                { range: '国三', score: '6' },
                { range: '省一', score: '6' },
                { range: '省二', score: '5' },
                { range: '省三', score: '4' },
                { range: '未获奖', score: '2' },
            ],
            //其他活动下拉数据
            selOtherScore: [
                { range: '院级', score: '1' },
                { range: '校级', score: '2' },
            ],
            typeGradeList: [],
            selGradeScore: [],
            ruleSonList: [],

            checkopen: false,
            // 操作类型1查看，2审核
            butType: 1,
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/labour/affirm/importData',
            },
            options: [],
            // 审核按钮状态
            isRefuse: false,
            isPass: false,
        };
    },
    created() {
        this.getTypeGrade();
        this.getList();
    },
    methods: {
        /** 查询个人荣誉认定列表 */
        getList() {
            this.loading = true;
            listAffirm(this.queryParams).then(response => {
                this.affirmList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /** 查询赋分规则下拉框 */
        getTypeGrade() {
            listTypeGrade().then(response => {
                console.log(response);
                this.typeGradeList = response.data;
            });
        },
        /** 查询学生 */
        remoteMethod(query) {
            if (query !== '') {
                this.loading = true;
                getstudentmanager(query).then(response => {
                    this.loading = false;
                    this.options = response.rows.filter(item => {
                        return item.label.toLowerCase()
                            .indexOf(query.toLowerCase()) > -1;
                    });
                });
            } else {
                this.options = [];
            }
        },
        changeProject(val) {
            // if(num==1){
            //     this.form.declareLevel = null;
            // }
            for (var i of this.typeGradeList) {
                if (val == i.type) {
                    this.selGradeScore = i.gradeList;
                    this.form.type = i.type;
                }
            }
        },
        changeSonProject(item) {
            this.form.childProject = item.name;
        },
        changeScore(item, index) {
            console.log(item, index, "ittt")
            // this.labourObjNameList[index - 1].declareLevel = item.range;
            // this.labourObjNameList[index - 1].nowScore = item.score;
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.checkopen = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                name: null,
                joinDate: null,
                remark: null,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加个人荣誉认定";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getAffirm(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.changeProject(this.form.type)
                this.title = "修改个人荣誉认定";
            });
        },
        /**审核按钮操作 */
        handleStatus(row, type) {
            if (type) {
                this.butType = type;
            }
            this.reset();
            const id = row.id || this.ids
            getAffirm(id).then(response => {
                this.form = response.data;
                this.title = "个人荣誉认定审核";
                this.isRefuse = false;
                this.isPass = false;
                this.form.status = null;
                this.checkopen = true;
            });
        },
        /** 提交按钮 */
        submitForm() {
            if (this.open) {
                // this.form.status = 0;
            }
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateAffirm(this.form).then(response => {
                            this.$modal.msgSuccess("操作成功");
                            this.open = false;
                            this.checkopen = false;
                            this.getList();
                        });
                    } else {
                        addAffirm(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除个人荣誉认定编号为"' + ids + '"的数据项？').then(function () {
                return delAffirm(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.open = true
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download(
                '/labour/affirm/importTemplate',
                {},
                `labour_${new Date().getTime()}.xlsx`
            );
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
                response.msg +
                '</div>',
                '导入结果',
                { dangerouslyUseHTMLString: true }
            );
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        submitFormE(val) {
            this.form.status = val;
            if (val == 1) {
                this.isRefuse = false;
                this.isPass = true;
            } else {
                this.isRefuse = true;
                this.isPass = false;
            }
        },
        // 审核提交
        statusSubmitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    var prams = {
                        id: this.form.id,
                        status: this.form.status,
                        auditOpinion: this.form.auditOpinion,
                    }
                    auditAffirm(prams).then(response => {
                        this.$modal.msgSuccess("审核成功");
                        this.checkopen = false;
                        this.getList();
                    });
                }
            });
        },
    }
};
</script>
